package com.zh.view.pane

import androidx.compose.foundation.Image
import androidx.compose.foundation.VerticalScrollbar
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollbarAdapter
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ClearAll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import com.zh.filetransport.contrl.CommandChat
import com.zh.view.ChatMsg
import com.zh.view.component.ChatBubble
import com.zh.view.component.TopBar
import com.zh.view.data.AppStore
import com.zh.view.data.ChatStore
import com.zh.view.data.ElMessage
import java.util.*

/**
 *
 * @author Zhou
 * @date 20:46 2025/5/30
 */

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChatPane() {
    // 从resources目录加载图片（确保图片在src/main/resources/images/目录下）
    val painter = painterResource("images/wallpaper_chat.jpeg")
    val chatMessages = remember { ChatStore.messages() }
    // 背景图片
    Image(
        painter = painter,  // 使用painter参数
        contentDescription = "聊天界面背景",
        modifier = Modifier
            .fillMaxSize()
            .alpha(0.6f), // 降低透明度
        contentScale = ContentScale.Crop // 裁剪图片以填充整个区域
    )

    var inputText by remember { mutableStateOf("") }

    val clickSend = fun() {
        var text = inputText.trim()

        //判断消息是否超长
        if (text.toByteArray().size >= 1024) {
            ElMessage.error("消息发送失败了")
            return
        }

        if (text.matches(Regex("^\\[.*]$"))) {
            text = text.substring(1, text.length - 1)
        }
        if (text.isNotEmpty()) {
            val chatMsg = ChatMsg(UUID.randomUUID().toString().takeLast(8), text, true)
            //发送消息
            if (!CommandChat(text, AppStore.peerIp.value)) {
                chatMsg.isFail = true
                ElMessage.error("消息发送失败了");
            }
            ChatStore.addToList(chatMsg)
            inputText = ""
        }
    }

    val scrollState = rememberLazyListState()

    Column {
//        TopBar("对话框")
        TopBar("对话框",actions = { // 添加右侧操作按钮
            IconButton(onClick = { ChatStore.removeAll()}) {
                Icon(
                    imageVector = Icons.Default.ClearAll,
                    contentDescription = "清除全部",
                    tint = MaterialTheme.colorScheme.onSurface
                )
            }
        })

        Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
            //1.聊天区域（限制高度，占剩余空间）
            Box(
                modifier = Modifier
                    .weight(1f) // 占满除输入框外的所有空间
            ) {
                LazyColumn(
                    modifier = Modifier.fillMaxSize(),
                    state = scrollState,
                    contentPadding = PaddingValues(end = 8.dp) // 为滚动条留出空间
                ) {
                    items(chatMessages) { message ->
                        ChatBubble(data = message, message.self)
                    }
                }
                // 为 LazyColumn 添加滚动条
                VerticalScrollbar(
                    modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(),
                    adapter = rememberScrollbarAdapter(scrollState),
                )
            }

            // 2. 输入框区域（固定高度，不被挤压）
            Spacer(modifier = Modifier.height(16.dp)) // 分隔符
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically
            ) {
                OutlinedTextField(
                    value = inputText,
                    onValueChange = { inputText = it },
                    modifier = Modifier.weight(1f).padding(end = 8.dp),
                    placeholder = { Text("input...") },
                    shape = RoundedCornerShape(16.dp)
                )
                Button(
                    onClick = clickSend,
                    shape = RoundedCornerShape(16.dp)
                ) {
                    Text("Sent")
                }
            }
        }
    }


}
